<%-- 
    Document   : create_article
    Created on : Feb 1, 2012, 3:26:41 PM
    Author     : yzaretskyy
--%>

<%@page import="java.net.URL"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
    // TODO: change this by AppContentHelper
    String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "" + request.getContextPath();
%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Create article</title>
        <script type="text/javascript">
            var $dialogSetArticleTitle;
            var $dialogAddBlock;
            var $rticleTitle;
            var $articleBody;
            var $dialogTitle;
            var $dialogBlockText;
            var $dialogBlockTitle;
            var $dialogSectionTitleDiv;
            var $dialogSectionTitle;
            var $parentSection;
            var $parentSecion;
            var $currentSection = null;
            var $addSectionOkButton;
            var $addParagraphOkButton;
            var index = 0;
            var sectionIndex = 100;
            var $selectedParagraph = null;
            
            $(document).ready(function() {
                $dialogSetArticleTitle = $("#addTitleDialog");
                $dialogAddBlock = $("#addBlockDialog");
                $articleTitle = $("#articleTitle");
                $articleBody = $("#articleBody");
                $dialogTitle = $("#dialogAdticleTitle");
                $dialogBlockText = $("#dialogBlockText");
                $dialogBlockTitle = $("#addBlockTitle");
                $dialogSectionTitleDiv = $("#dialogSectionTitleDiv");
                $dialogSectionTitle = $("#dialogSectionTitle");
                $parentSection =$("#parentSection");
                $addSectionOkButton = $("#addSectionOkButton");
                $addParagraphOkButton = $("#addParagraphOkButton");
                $(".row").live("mouseenter", function() {
                    $(this).find(".blockTextStyle").toggleClass("hoverUser").end().find(".sectionLinks .manageSectionLinks").fadeIn("fast");
                }).live("mouseleave", function() {
                    $(this).find(".blockTextStyle").toggleClass("hoverUser").end().find(".sectionLinks .manageSectionLinks").fadeOut("fast");
                });
                
                $(".paragraph").live("mouseenter", function() {
                    $(this).toggleClass("hoverUser");
                }).live("mouseleave", function() {
                    $(this).toggleClass("hoverUser");
                });
                
                $dialogSetArticleTitle.bind("keypress", function(e) {
                    var code = (e.keyCode ? e.keyCode : e.which);
                    if(code == 13) {
                        setTitle();
                    } else if(code == 27) {
                        $dialogSetArticleTitle.fadeOut();
                    }
                });
                
                $(".paragraph").live("click", function() {
                    $(this).attr("contentEditable", "true");
                }).live("focusout", function() {
                    $(this).attr("contentEditable", "false");
                });
                
                $articleBody.find("div").each(function() {
                    var $elem = $(this);
                    if(!$elem.attr("class")) {
                        $elem.addClass("articleBlock section blockTextStyle pointer");
                    }
                }).end().find("p").each(function() {
                    $(this).addClass("articleBlock paragraph");
                }).end().find("h3").each(function() {
                    $(this).addClass("sectionTitle");
                });
            });
            
            function isValidSectionFields() {
                return $.trim($dialogSectionTitle.val()) != "" && $.trim($dialogBlockText.val()) != "";
            }
            
            function isValidParagraphFields() {
                return $.trim($dialogBlockText.val()) != "";
            }
            
            function isValidTitle() {
                return $.trim($dialogTitle.val()) != "";
            }
        
        <c:if test="${createArticle || canCreate || canEdit || canDelete || docBlocks != null}">            
            function getSections() {
                var sectionsIds = new Array();
                var sections = new Array();
                $(".section").each(function() {
                    var $elem = $(this).clone();
                    $elem.removeAttr("class").find("h3").removeAttr("class");
                    $elem.find("p").remove();
                    sectionsIds.push($elem.attr("id"));
                    sections.push($elem.outerHTML());
                });
                return {ids: sectionsIds, data: sections};
            }
            
            function createUpdateArticle() {
                var hierarchy = generateHierarchy();
                var blocks = new Array();
                var blocksIds = new Array();
                $(".paragraph").each(function() {
                    var $elem = $(this).clone();
                    $elem.removeAttr("class");
                    blocks.push($elem.outerHTML());
                    blocksIds.push($elem.attr("id"));
                });
                var sectionsInfo = getSections();
                blocks = blocks.concat(sectionsInfo.data);
                blocksIds = blocksIds.concat(sectionsInfo.ids);
                var $article = $("#article");
                $.ajax({
                    traditional: true,
                    url: "<%=url%>/article/save_or_update_article.html",
                    type: "POST",
                    data: {
                        docId: $article.attr("articleId") ? $.trim($article.attr("articleId")) : "",
                        articleTitle: $.trim($articleTitle.html()),
                        hierarchy: $.trim(hierarchy),
                        docBlocksId: blocksIds,
                        docBlocksData: blocks},
                    success: function(docId) {
                        window.location = "<%=url%>/article/view/" + docId + ".html";
                    }
                });
            }
        </c:if>
            
        <c:if test="${createArticle || canEdit || canCreate || docBlocks != null}">
            function showSetTitle($section) {
                $currentSection = $section && $section.length != 0 ? $section.parent() : null;
                $dialogTitle.val($currentSection ? $section.html() : $.trim($articleTitle.html()));
                $dialogSetArticleTitle.modal();
            }
            
            function setTitle() {
                if(isValidTitle()) {
                    try {
                        if($currentSection) {
                            $currentSection.find("h3").html($.trim($dialogTitle.val()));
                        } else {
                            $articleTitle.html($.trim($dialogTitle.val()));
                        }
                        closeDialog($dialogSetArticleTitle);
                    } finally {
                        $currentSection = null;
                    }
                }
            }
        </c:if>
            
            function closeDialog($dialog) {
                $dialog.modal("hide")
            }

        <c:if test="${createArticle || canCreate || docBlocks != null}">
            function showAddSection($parent) {
                $currentSection = $parent;
                $dialogSectionTitleDiv.show();
                $dialogSectionTitle.val("");
                $dialogBlockTitle.html("Add Section");
                $dialogBlockText.val($currentSection && $currentSection.length != 0 ? $currentSection.html() : "");
                $addSectionOkButton.show();
                $addParagraphOkButton.hide();
                $dialogAddBlock.modal();
            }
            
            function addSection($parent) {
                if(isValidSectionFields()) {
                    if(!$parent || ($parent && $parent.length == 0)) $parent = $articleBody;
                    index = sectionIndex + 1;
                    var blockId = Math.uuidCompact();
                    $parent.append("<div class='row'>\n\
                                        <div class='sectionLinks'>\n\
                                            <span class='manageSectionLinks hide'>\n\
                                                <a class='pointer' onclick='showSetTitle($(this).parent().parent().parent().find(\".blockTextStyle h3\"))'>Change title</a><br/>\n\
                                                <a class='pointer' onclick='showAddParagraph($(this).parent().parent().parent().find(\".blockTextStyle\"))'>Add paragraph</a><br/>\n\
                                                <a class='pointer' onclick='removeBlock($(this).parent().parent().parent())'>Remove section</a><br/>\n\
                                            </span>\n\
                                        </div>\n\
                                        <div class='articleBlock section blockTextStyle pointer' index='" + (sectionIndex) + "' id='" + blockId + "' sectionTitle='" + $.trim($dialogSectionTitle.val()) + "'>\n\
                                            <h3 class='sectionTitle'>"+$.trim($dialogSectionTitle.val())+"</h3>\n\
                                            <p class='articleBlock paragraph' parent='" + blockId + "' id='" + Math.uuidCompact() + "' index='" + (index++) + "'>"+$.trim($dialogBlockText.val()).replace(/\n/g, "<br/>")+"</p>\n\
                                        </div>\n\
                                    </div>");
                    closeDialog($dialogAddBlock);
                    sectionIndex += 100;
                }
            }
            
            function showAddParagraph($parent) {
                $currentSection = $parent && $parent.length != 0 ? $parent : null;
                $dialogSectionTitleDiv.hide();
                $dialogBlockTitle.html("Add Paragraph");
                $dialogBlockText.val("");
                $addSectionOkButton.hide();
                $addParagraphOkButton.show();
                $dialogAddBlock.modal();
            }
            
            function addParagraph() {
                if(isValidParagraphFields()) {
                    try {
                        index = parseInt($currentSection.find("p:last").attr("index"), 10) + 1;
                        var $newParagraph = $("<p class='articleBlock paragraph' parent='" + $currentSection.attr("id") + "' id='" + Math.uuidCompact() + "' index='" + (index++) + "'></p>");
                        $currentSection.append($newParagraph);
                        $newParagraph.html($.trim($dialogBlockText.val()).replace(/\n/g, "<br/>"));
                    } finally {
                        $currentSection = null;
                    }
                    closeDialog($dialogAddBlock);
                }
            }
        </c:if>
         
        <c:if test="${createArticle || canDelete}">
            function removeBlock($block) {
                $block.remove();
            }
        </c:if>  
            
            function getParentId($elem) {
                return $elem[0].tagName == "body" ? "" : $elem.parent().attr("id");
            }
            
            $.fn.outerHTML = function() {
                return $.trim($("<p>").append(this.clone()).html());
            }
            
            function generateHierarchy() {
                var $bodyClone = $articleBody.clone();
                $bodyClone.find(".sectionLinks").remove();
                $bodyClone.find(".paragraph").html("");
                var hierarchy = "";
                $bodyClone.find(".articleBlock").each(function() {
                    var $elem = $(this);
                    hierarchy += ($elem.attr("class").indexOf("section") != -1 ? "<section " : "<paragraph ") + 
                        "id='" + $elem.attr("id") + 
                        "' parent='"+ ($elem.attr("parent") ? $elem.attr("parent") : "-1") + 
                        "' index='"+ $elem.attr("index") + "'" +
                        ($elem.attr("sectionTitle") ? (" sectionTitle='" + $elem.attr("sectionTitle") +"'") : "") +
                        ($elem.attr("class").indexOf("section") != -1 ? ">" : "/>") + 
                        "<newlineseparartor>";
                });
                return hierarchy.substring(0, hierarchy.length - 19);
            }
            
            Math.uuidCompact = function() {
                return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
                    return v.toString(16);
                });
            };
        </script>
    </head>
    <body>
        <div style="width: 80%; margin-left:10%">
            <h1 style="text-align: center; margin-left: 10%">Create Article</h1>
            <div style="margin-left: 10%">
                <c:if test="${createArticle || canEdit || canCreate || docBlocks != null}">
                    <a class="btn" onclick="showSetTitle()"><i class="icon-edit"></i> Set Article Title</a>
                </c:if>
                <c:if test="${createArticle || canCreate || docBlocks != null}">
                    <a class="btn" onclick="showAddSection()"><i class="icon-edit"></i> Add section</a>
                </c:if>
                <c:if test="${createArticle || canCreate || canEdit || canDelete || docBlocks != null}">
                    <a class="btn btn-primary" onclick="createUpdateArticle()" style="position: absolute; right: 10%"><i class="icon-ok icon-white"></i> Create article</a>
                </c:if>
                <hr/>
            </div>
            <div style="margin-top: 10px;">
                <c:choose>
                    <c:when test="${article != null}">
                        <div id="article" articleId="${article.id}" style="width: 100%; height: 500px; resize: none;">
                    </c:when>
                    <c:otherwise>
                        <div id="article" style="width: 100%; height: 500px; resize: none;">
                    </c:otherwise>
                </c:choose>
                    <h2 id="articleTitle">
                        <c:if test="${article != null}">
                            ${article.title}
                        </c:if>
                    </h2>
                    <div id="articleBody">
                        <c:if test="${docBlocks != null}">
                            <c:forEach items="${docBlocks}" var="docBlock">
                                <div class='row'>
                                    <div class='sectionLinks'>
                                        <span class='manageSectionLinks hide'>
                                            <a class="pointer" onclick="showSetTitle($(this).parent().parent().parent().find('.blockTextStyle h3'))">Change title</a><br/>
                                            <a class="pointer" onclick="showAddParagraph($(this).parent().parent().parent().find('.blockTextStyle'))">Add paragraph</a><br/>
                                            <a class="pointer" onclick="removeBlock($(this).parent().parent().parent())">Remove section</a><br/>
                                        </span>
                                    </div>
                                    ${docBlock.data}
                                </div>
                            </c:forEach>
                        </c:if>
                    </div>
                </div>
            </div>
        </div>
         
  <c:if test="${createArticle || canCreate || canEdit || docBlocks != null}">
        <!-- set title dialog -->
        <div id="addTitleDialog" class="modal hide fade">
            <div class="modal-header">
                <a class="close" data-dismiss="modal">×</a>
                <h3>Set Title</h3>
            </div>

            <div class="modal-body form-horizontal">
                <div class="control-group">
                    <label for="dialogArticleTitle" class="control-label">
                        Title:
                    </label>
                    <div class="controls">
                        <input id="dialogAdticleTitle" style="width: 300px;" type="text" required/>
                    </div>
                </div>
            </div>

            <div class="modal-footer">
                <input type="button" class="btn btn-primary" value="Ok" onclick="setTitle()"/>
                <input type="button" class="btn" value="Cancel" onclick="closeDialog($dialogSetArticleTitle);"/>
            </div>
        </div>
        <!-- end set title dialog -->

        <!-- add section dialog -->
        <div id="addBlockDialog" class="modal hide fade">
            <div class="modal-header">
                <a class="close" data-dismiss="modal">×</a>
                <h3 id="addBlockTitle"></h3>
            </div>

            <div class="modal-body">
                <input type="hidden" id="parentSection" />
                <div id="dialogSectionTitleDiv" class="control-group hide">
                    <label for="dialogSectionTitle">Section title</label>
                    <div class="controls">
                        <input type="text" id="dialogSectionTitle" required/>
                    </div>
                </div>
                <div class="control-group">
                    <label for="dialogBlockText" id="addBlockLabel">Paragraph text</label>
                    <div class="controls">
                        <textarea id="dialogBlockText" rows="7" style="resize: none; width: 100%" required></textarea>
                    </div>
                </div>
            </div>

            <div class="modal-footer">
                <input id="addSectionOkButton" type="button" class="btn btn-primary" value="Ok" onclick="addSection()" />
                <input id="addParagraphOkButton" type="button" class="btn btn-primary" value="Ok" onclick="addParagraph()" />
                <input type="button" class="btn" value="Cancel" onclick="closeDialog($dialogAddBlock)" />
            </div>
        </div>
        <!-- end add block dialog -->
  </c:if>
    </body>
</html>